// pages/home/repair/user-repair/userRepair.js
import {
    fetchData,
    getRequest,
    postRequest
} from '../../../../utils/request'
const app = getApp();
const baseUrl = app.globalData.root;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        deviceId: "", //设备id
        fileList: [],
        repairUsers: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
        device: {},
        show: false,
        repair: {},
        troubleXh: "",
        troubleWhy: "",
        troubleBw: "",
        userId:""
    },
    showPopup() {
        this.setData({
            show: true
        });
    },
    /**
     * 获取检修负责人列表
     */

    async getOverhaulPersonList() {
        const result = await getRequest("/base/repair/getRepairUserList", "")
        if (result.code == 200) {
            this.setData({
                repairUsers: result.data
            })
        }
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    bindPickerChange: function(e) {
        this.setData({
            userId: e.detail.value,
            ['device.overhaulPerson']: this.data.repairUsers[e.detail.value]
        })
      },
    uploadMinio(url) {
        let that = this
        wx.showLoading();
        let token = wx.getStorageSync('token')
        wx.uploadFile({
            url: baseUrl + '/common/uploadMinio', // 仅为示例，非真实的接口地址
            filePath: url,
            header: {
                'Authorization': "Bearer " + token,
            },
            name: 'file',
            success(res) {
                wx.hideLoading();
                if (res.statusCode == 200) {
                    let data = JSON.parse(res.data)
                    let url = data.url
                    if (url) {
                        let item = {
                            url: url,
                            name: "上传图片"
                        }
                        let fileList = that.data.fileList
                        fileList.push(item)
                        that.setData({
                            fileList: fileList
                        })
                        console.log(that.data.fileList);
                    }
                }
            },
            fail(err) {
                console.log(err);
            }
        });
    },
    /**
     * 
     * @param {上传} event 
     */
    afterRead(event) {
        const {
            file
        } = event.detail;
        this.uploadMinio(file.url)


        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

    },
    /**
     * 提交表单
     */
    async sumbitForm() {
      let {userId}=  wx.getStorageSync('user');
        const {
            dvName,
            dvCode,
            overhaulPerson,
            dvTypeCode,
            useDept,
            id
        } = this.data.device
        const troubleImg = this.data.fileList[0].url
        this.setData({
            ['repair.dvName']: dvName,
            ['repair.dvCode']: dvCode,
            ['repair.repairUser']: overhaulPerson,
            ['repair.usePart']: useDept,
            ['repair.cvType']: dvTypeCode,
            ['repair.troubleImg']: troubleImg,
            ['repair.troubleBw']: this.data.troubleBw,
            ['repair.troubleWhy']: this.data.troubleWhy,
            ['repair.troubleXh']: this.data.troubleXh,
            ['repair.userId']:userId,
            ['repair.dvId']:id
        })
        wx.showLoading()
        const result = await postRequest('/base/repair/submitRepair', this.data.repair)
      if(result.code==200){
          wx.hideLoading()
        wx.showToast({
            title: '提交成功',
        })
        wx.navigateBack()
      }
    },
    async scanCodeGetDevice() {
        let deviceId = await this.scanCodeBindDevice()
        console.log(deviceId);
        if (deviceId) {
            this.getDeviceByDvCode(deviceId)
        }
    },
    async getDeviceByDvCode(dvCode) {
        const {
            data,
            code
        } = await getRequest(`/base/device/getInfoByDvCode?dvCode=${dvCode}`, "")
        if (code == 200) {
            this.setData({
                device: data
            })
        }
    },
    /**
     * 扫描绑定设备
     */
    scanCodeBindDevice() {
        return new Promise((resolve, reject) => {
            wx.scanCode({
                success: res => {
                    let deviceId = res.result
                    if (deviceId) {
                        resolve(deviceId)
                    }
                },
                fail: err => {
                    reject(err)
                    wx.showToast({
                        title: err.msg,
                        icon: "error"
                    })
                }
            })
        })

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getOverhaulPersonList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})